package com.gegong.imr.client.vbox.cmd;


import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.virtualbox_5_2.*;

/**
 * 虚拟机电源命令
 */
@Slf4j
public class VMPowerCmd extends AbstractVBoxCmd {


    public VMPowerCmd(@NonNull VirtualBoxManager virtualBoxManager, @NonNull String targetVm) {
        super(virtualBoxManager, targetVm);
    }

    private VmPowerOption powerOption;
    private IMachine targetMachine;

    @Override
    public Progress execute(Object... params) {

        try {
            powerOption = (VmPowerOption) params[0];
            super.execute(params);
            targetMachine = getVirtualBox().findMachine(getTargetVm());

            IProgress powerProgress;
            switch (powerOption) {
                case ON:
                    powerProgress = powerOn();
                    break;
                case OFF:
                    powerProgress = powerOff();
                    break;
                case RESTART:
                    powerProgress = powerRestart();
                    break;
            }


        } catch (Exception e) {
            progress.resultCode = Progress.RESULT_FAILURED;
            progress.errorInfo = e;
        } finally {
            progress.completed = true;
        }


        return progress;
    }

    private IProgress powerOn() {
        IProgress progress = targetMachine.launchVMProcess(getVirtualBoxManager().getSessionObject(), "headless", null);
        progress.waitForCompletion(TimeOuts.NONE);
        log.info("虚拟机{}启动进度{},启动{}", getTargetVm(), progress.getPercent(), progress.getCompleted() ? "成功" : "失败");
        return progress;
    }


    private IProgress powerOff() throws Exception {
        ISession machineSession = getVirtualBoxManager().openMachineSession(targetMachine);
        IConsole console = machineSession.getConsole();
        IProgress progress = console.powerDown();
        progress.waitForCompletion(TimeOuts.NONE);
        log.info("虚拟机{}关闭进度{},关闭{}", getTargetVm(), progress.getPercent(), progress.getCompleted() ? "成功" : "失败");

        return progress;
    }


    private IProgress powerRestart() throws Exception {
        powerOff();
        return powerOn();
    }

    @Override
    public String getName() {
        return String.format("虚拟机%s-%s电源", getTargetVm(), powerOption.getLabel());
    }
}
